package ddd.ajava.chapter4.question1;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class PersonDisplay implements PersonAction {

	@Override
	public Person process(Person person) {
		List<String> list = this.showLabelValue(person.getClass());//注解
		List<String> list2=this.getAttr(person, person.getClass());
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i)+list2.get(i));
		}
		return null;
	}
	//通过obj调用get方法，获取属性值
	private List<String> getAttr(Object obj,Class<?> clazz) {
		Field fields[] = clazz.getDeclaredFields();
		Method methods[] = clazz.getDeclaredMethods();
		List<String> list=new ArrayList<String>();
		try {
			for (int i = 0; i < fields.length; i++) {
				
				if(fields[i].getType().getName()=="java.lang.Boolean"){
					String setter="is"+StringUtil.firstCharToUp(fields[i].getName());
					for(Method method:methods){
						String methodName=method.getName();
						if(methodName.equals(setter)){
							list.add((String)method.invoke(obj).toString());
//							System.out.println(methodName);
							break;
						}
					}
				}else {
					String setter="get"+StringUtil.firstCharToUp(fields[i].getName());
					for(Method method:methods){
						String methodName=method.getName();
						if(methodName.equals(setter)){
							list.add((String)method.invoke(obj).toString());
//							System.out.println(methodName);
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// 获取标注的名称
	private List<String> showLabelValue(Class<?> clazz) {
		List<String> list = new ArrayList<String>();
		Field fields[]= clazz.getDeclaredFields();
		for(Field field:fields){
//			Class cl=field.getType();
			Label lb=field.getAnnotation(Label.class);
			list.add(lb.name()+":");
		}
		return list;
	}
}
